# Maintainer: J. Peter Mugaas <jpmugaas@suddenlink.net>
# Maintainer: Naveen M K <naven@syrusdark.website>

_realname=distlib
pkgbase=mingw-w64-python-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-python-${_realname}")
provides=("${MINGW_PACKAGE_PREFIX}-python3-${_realname}")
conflicts=("${MINGW_PACKAGE_PREFIX}-python3-${_realname}")
replaces=("${MINGW_PACKAGE_PREFIX}-python3-${_realname}")
pkgver=0.3.3
pkgrel=1
pkgdesc="Low-level components of distutils2/packaging (mingw-w64)"
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clang32' 'clangarm64')
url="https://bitbucket.org/pypa/${_realname}"
license=('FSF')
depends=("${MINGW_PACKAGE_PREFIX}-python")
makedepends=("${MINGW_PACKAGE_PREFIX}-python-setuptools")
options=('staticlibs' 'strip' '!debug')
source=("https://files.pythonhosted.org/packages/source/${_realname:0:1}/${_realname}/${_realname}-${pkgver}.zip")
sha256sums=('d982d0751ff6eaaab5e2ec8e691d949ee80eddf01a62eaa96ddb11531fe16b05')

prepare() {
  cd "${srcdir}"
  rm -rf python-build-${CARCH} | true
  cp -r "${_realname}-${pkgver}" "python-build-${CARCH}"

  # Set version for setuptools_scm
  export SETUPTOOLS_SCM_PRETEND_VERSION=${pkgver}
}

build() {
  cd "${srcdir}/python-build-${CARCH}"

  rm -f distlib/{w,t}{32,64}{,-arm}.exe
  local _gui_cflags="-DWIN32 -DNDEBUG -D_WINDOWS -mwindows -O2"
  local _cli_cflags="-DWIN32 -DNDEBUG -D_CONSOLE -O2"
  local _gui_lflags="-lshlwapi"
  local _cli_lflags="-lshlwapi"
  if check_option "strip" "y"; then
    _gui_cflags+=" -s"
    _cli_cflags+=" -s"
  fi
  case "$MSYSTEM" in
  MINGW*)
    _gui_cflags+=" -mcrtdll=msvcr120"
    _cli_cflags+=" -mcrtdll=msvcr120"
    ;;
  esac
  windres --input PC/launcher.rc --output PC/resources.res --output-format=coff

  case "${MINGW_CHOST}" in
  i686-w64-mingw32)
    cc $_cli_cflags -o distlib/t32.exe PC/launcher.c PC/resources.res $_cli_lflags
    cc $_gui_cflags -o distlib/w32.exe PC/launcher.c PC/resources.res $_gui_lflags
    ;;
  x86_64-w64-mingw32)
    cc $_cli_cflags -o distlib/t64.exe PC/launcher.c PC/resources.res $_cli_lflags
    cc $_gui_cflags -o distlib/w64.exe PC/launcher.c PC/resources.res $_gui_lflags
    ;;
  aarch64-w64-mingw32)
    cc $_cli_cflags -o distlib/t64-arm.exe PC/launcher.c PC/resources.res $_cli_lflags
    cc $_gui_cflags -o distlib/w64-arm.exe PC/launcher.c PC/resources.res $_gui_lflags
    ;;
  *)
    echo "Unsupported CHOST ${MINGW_CHOST}" && false
    ;;
  esac

  ${MINGW_PREFIX}/bin/python setup.py build
}

check() {
  msg "Python test for ${CARCH}"
  cd "${srcdir}/python-build-${CARCH}"
  PYTHONHASHSEED=0 ${MINGW_PREFIX}/bin/python setup.py test || warning "Tests failed"
}

package() {
  cd "${srcdir}/python-build-${CARCH}"
  MSYS2_ARG_CONV_EXCL="--prefix=;--install-scripts=;--install-platlib=" \
    ${MINGW_PREFIX}/bin/python setup.py install --prefix=${MINGW_PREFIX} \
    --root="${pkgdir}" --optimize=1 --skip-build
}
